package pers.xx.sbm.service.serviceImpl;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xx.sbm.dao.ReportDataMapper;
import pers.xx.sbm.service.ReportDataService;
import pers.xx.sbm.vo.ProjectIndicatorsVo;
import pers.xx.sbm.vo.TotalSampleVo;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportDataServiceImpl implements ReportDataService {

    @Autowired
    private ReportDataMapper reportDataMapper;

    private static int CURRENT_YEAR = LocalDate.now().getYear() - 1;
    private Integer studentCount = 0;
    private Integer parentCount = 0;
    private Integer teacherCount = 0;
    private Integer yzCount = 0;
    private Integer rddbCount = 0;
    private Integer total = 0;
    private Double totalSatisfaction = 0.0;
    private List<TotalSampleVo> areaSatisfaction = Collections.EMPTY_LIST;
    private Double xdSatisfaction = 0.0;
    private List<TotalSampleVo> xdSatisfactionList = Collections.EMPTY_LIST;

    private void inintTotalCount() {
        if (total == 0) {
            List<TotalSampleVo> result = reportDataMapper.queryRoleTotalSample();
            for (TotalSampleVo totalSample : result) {
                if (totalSample.getName().equals("教师")) {
                    teacherCount += Integer.parseInt(totalSample.getValue().toString());
                }
                if (totalSample.getName().equals("教职工")) {
                    teacherCount += Integer.parseInt(totalSample.getValue().toString());
                }
                if (totalSample.getName().equals("学生")) {
                    studentCount += Integer.parseInt(totalSample.getValue().toString());
                }
                if (totalSample.getName().equals("家长")) {
                    parentCount += Integer.parseInt(totalSample.getValue().toString());
                }
                if (totalSample.getName().equals("园长")) {
                    yzCount += Integer.parseInt(totalSample.getValue().toString());
                }
                if (totalSample.getName().equals("人大代表/政协委员")) {
                    rddbCount += Integer.parseInt(totalSample.getValue().toString());
                }
            }

            total = studentCount + parentCount + teacherCount + yzCount + rddbCount;
        }
    }

    private void inintTotalSatisfaction() {
        if (totalSatisfaction == 0) {
            List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole("", "");
            for (TotalSampleVo totalSample : result) {
                totalSatisfaction += Double.parseDouble(totalSample.getValue().toString());
            }
            areaSatisfaction = result;
        }
    }

    private void inintXdSatisfaction() {
        if (xdSatisfaction == 0) {
            List<TotalSampleVo> result = reportDataMapper.queryXdSatisfaction();
            for (TotalSampleVo totalSample : result) {
                xdSatisfaction += Double.parseDouble(totalSample.getValue().toString());
            }
            xdSatisfactionList = result;
        }
    }

    @Override
    public String queryRoleTotalSample() {
        inintTotalCount();
        return String.format(CURRENT_YEAR + "年调查样本%d人，其中，学生%d人、教师%d人、家长%d人、幼儿园园长%d人、人大代表/政协委员%d人。各人群样本数量与" + (CURRENT_YEAR - 2) + "年、" + (CURRENT_YEAR - 1) + "年的对比情况如图1所示。",
                total, studentCount, teacherCount, parentCount, yzCount, rddbCount);
    }

    @Override
    public Map<String, ArrayList<Integer>> queryXdTotalSample() {
        List<TotalSampleVo> result = reportDataMapper.queryXdTotalSample();
        Map<String, ArrayList<Integer>> dataMap = new HashMap();
        ArrayList<Integer> arrayYearBeforeLast = new ArrayList<Integer>();
        ArrayList<Integer> arrayLastYear = new ArrayList<Integer>();
        ArrayList<Integer> arrayCurrentYear = new ArrayList<Integer>();

        arrayYearBeforeLast.add(80900);
        arrayYearBeforeLast.add(164465);
        arrayYearBeforeLast.add(103165);
        arrayYearBeforeLast.add(50911);

        arrayLastYear.add(63814);
        arrayLastYear.add(234126);
        arrayLastYear.add(103022);
        arrayLastYear.add(59516);

        for (TotalSampleVo data : result) {
            arrayCurrentYear.add(Integer.parseInt(data.getValue().toString()));
        }

        dataMap.put(String.valueOf(CURRENT_YEAR - 2), arrayYearBeforeLast);
        dataMap.put(String.valueOf(CURRENT_YEAR - 1), arrayLastYear);
        dataMap.put(String.valueOf(CURRENT_YEAR), arrayCurrentYear);
        return dataMap;
    }

    @Override
    public String queryTotalSamplePercentage() {
        inintTotalCount();
        return String.format("覆盖全市十个区（市、县）的所有幼儿园、小学、初中和高中学校，共计调查学生 %d，教师 %d 人，家长 %d 人，幼儿园园长%d人，人大代表/政协委员%d人分别占比 %s、%s、%s、%s和 %s。",
                studentCount, teacherCount, parentCount, yzCount, rddbCount, getPercent(studentCount, total), getPercent(teacherCount, total), getPercent(parentCount, total), getPercent(yzCount, total), getPercent(rddbCount, total));
    }

    @Override
    public String queryRoleXdTotalSamplePercentage(String role) {
        String sentence = "";
        int yeyCount = 0;
        int xxCount = 0;
        int czCount = 0;
        int gzCount = 0;
        int totalCount = 0;
        List<TotalSampleVo> result = reportDataMapper.queryXdTotalSampleByRole(role);
        for (TotalSampleVo totalSample : result) {
            if (totalSample.getName().equals("幼儿园")) {
                yeyCount += Integer.parseInt(totalSample.getValue().toString());
            }
            if (totalSample.getName().equals("小学")) {
                xxCount += Integer.parseInt(totalSample.getValue().toString());
            }
            if (totalSample.getName().equals("初中")) {
                czCount += Integer.parseInt(totalSample.getValue().toString());
            }
            if (totalSample.getName().equals("高中")) {
                gzCount += Integer.parseInt(totalSample.getValue().toString());
            }
        }
        totalCount = yeyCount + xxCount + czCount + gzCount;
        if (role.equals("学生")) {
            sentence = String.format("在调查的%d名学生中，小学生、初中生和高中生分别占比 %s、%s和%s，学段区县分布比例分别如图2和图3所示。",
                    totalCount, getPercent(xxCount, totalCount), getPercent(czCount, totalCount), getPercent(gzCount, totalCount));
        }
        if (role.equals("教师")) {
            sentence = String.format("在调查的%d名教师中，幼儿园、小学、初中和高中教师占比分别为%s、%s、%s和%s，学段和区县分布比例分别如图4和图5所示。",
                    totalCount, getPercent(yeyCount, totalCount), getPercent(xxCount, totalCount), getPercent(czCount, totalCount), getPercent(gzCount, totalCount));
        }
        if (role.equals("家长")) {
            sentence = String.format("在调查的%d名家长中，幼儿园、小学、初中和高中家长占比分别为%s、%s、%s和%s，学段和区县分布比例分别如图6和图7所示。",
                    totalCount, getPercent(yeyCount, totalCount), getPercent(xxCount, totalCount), getPercent(czCount, totalCount), getPercent(gzCount, totalCount));
        }
        if (role.equals("园长")) {
            sentence = String.format("全市调查了%d名幼儿园园长，", totalCount);
        }
        if (role.equals("人大代表/政协委员")) {
            sentence = String.format("全市针对幼儿园调查了%d名人大代表/政协委员，", totalCount);
        }
        return sentence;
    }

    @Override
    public List<TotalSampleVo> queryRoleXdTotalSample(String role) {
        List<TotalSampleVo> xdTotalSample = reportDataMapper.queryXdTotalSampleByRole(role);

        if (CollectionUtils.isEmpty(xdTotalSample)) {
            List<TotalSampleVo> result = new ArrayList<>();
            result.add(new TotalSampleVo("小学", 0));
            result.add(new TotalSampleVo("初中", 0));
            result.add(new TotalSampleVo("高中", 0));
            return result;
        }
        getDataPercent(xdTotalSample, true);
        return xdTotalSample;
    }

    @Override
    public List<Object> queryRoleAreaTotalSamplePercentage(String role) {
        return getDataValuePercent(reportDataMapper.queryAreaTotalSampleByRole(role), true);
    }

    @Override
    public String queryTotalSatisfaction() {
        inintTotalSatisfaction();
        //全市综合满意率
        String satisfiedRate = getSatisfiedRate(areaSatisfaction);
        //查询今年各区县满意水平
        List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole("", "");
        // 查询上年满意率
        List<TotalSampleVo> lastYear = reportDataMapper.queryAreaHistoryData("-1", "-1", String.valueOf(CURRENT_YEAR - 1));
        List<Double> lastYearTotal = reportDataMapper.queryHistoryData("","-1", "-1", String.valueOf(CURRENT_YEAR - 1));
        return "此次调查采集的数据分析显示，全市综合满意率" + satisfiedRate + compareLastYear(satisfiedRate, lastYearTotal.get(0) + "%") + "。其中，" + getAreaRateString(areaSatisfaction,"") + currentYearcompareLastYear(result, lastYear,5,"区县");
    }

    @Override
    public Map<String, List<Double>> queryAreaSamplePercentage() {
        Map<String, List<Double>> dataMap = new HashMap();
        List<Double> arrayYearBeforeLast = reportDataMapper.queryHistoryData("","-1", "-1", String.valueOf(CURRENT_YEAR - 2));
        List<Double> arrayLastYear = reportDataMapper.queryHistoryData("","-1", "-1", String.valueOf(CURRENT_YEAR - 1));
        ArrayList<Double> arrayCurrentYear = new ArrayList<Double>();

        String satisfiedRate = getSatisfiedRate(areaSatisfaction);
        arrayCurrentYear.add(Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1)));

        for (TotalSampleVo data : areaSatisfaction) {
            arrayCurrentYear.add(getPercentNo(Double.parseDouble(data.getValue().toString()), 5));
        }


        dataMap.put(String.valueOf(CURRENT_YEAR - 2), arrayYearBeforeLast);
        dataMap.put(String.valueOf(CURRENT_YEAR - 1), arrayLastYear);
        dataMap.put(String.valueOf(CURRENT_YEAR), arrayCurrentYear);
        return dataMap;
    }

    @Override
    public String queryXdSatisfaction() {
        inintXdSatisfaction();
        //查询今年各学段满意水平
        List<TotalSampleVo> result = reportDataMapper.queryXdSatisfaction();
        // 查询上年满意率
        List<TotalSampleVo> lastYear = reportDataMapper.queryXdHistoryData("-1", String.valueOf(CURRENT_YEAR - 1));
        return CURRENT_YEAR + "年全市四个学段综合满意率从高到低分别为：" + getXdRateString(xdSatisfactionList) + currentYearcompareLastYear(result,lastYear,5*12,"阶段");
    }

    @Override
    public Map<String, List<Double>> queryXdSamplePercentage() {
        Map<String, List<Double>> dataMap = new HashMap();
        ArrayList<Double> arrayCurrentYear = new ArrayList<Double>();


        List<Double> arrayLastYear = reportDataMapper.queryXdHistoryDataByYear(String.valueOf(CURRENT_YEAR - 1));

        List<Double> arrayYearBeforeLast = reportDataMapper.queryXdHistoryDataByYear(String.valueOf(CURRENT_YEAR - 2));


        String satisfiedRate = getSatisfiedRate(xdSatisfactionList);
        double sum = Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1));
        arrayCurrentYear.add(Double.parseDouble(String.format("%.2f", sum / 12)));

        for (TotalSampleVo data : xdSatisfactionList) {
            arrayCurrentYear.add(getPercentNo(Double.parseDouble(data.getValue().toString()), 5 * 12));
        }


        dataMap.put(String.valueOf(CURRENT_YEAR - 2), arrayYearBeforeLast);
        dataMap.put(String.valueOf(CURRENT_YEAR - 1), arrayLastYear);
        dataMap.put(String.valueOf(CURRENT_YEAR), arrayCurrentYear);
        return dataMap;
    }

    @Override
    public String queryAreaSatisfactionByRole(String role) {
        List<TotalSampleVo> areaSatisfactionRole = reportDataMapper.queryAreaSatisfactionByXdAndRole("", role);
        //全市综合满意率
        String satisfiedRate = getSatisfiedRate(areaSatisfactionRole);
        if(role.equals("园长") || role.equals("人大代表/政协委员")) {
            return "全市" + role + "综合满意率" + satisfiedRate + "。其中，" + getAreaRateString(areaSatisfactionRole,role);
        }
        // 查询上年满意率
        List<TotalSampleVo> lastYear = reportDataMapper.queryAreaHistoryData("-1", role,String.valueOf(CURRENT_YEAR - 1));
        return "全市" + role + "综合满意率" + satisfiedRate + "。其中，" + getAreaRateString(areaSatisfactionRole,role) + currentYearcompareLastYear(areaSatisfactionRole,lastYear,5,"");
    }

    @Override
    public Map<String, List<Double>> queryAreaSatisfactionPercentageByRole(String role) {
        Map<String, List<Double>> dataMap = new HashMap();
        List<Double> arrayYearBeforeLast = reportDataMapper.queryHistoryData("","-1", role, String.valueOf(CURRENT_YEAR - 2));
        List<Double> arrayLastYear = reportDataMapper.queryHistoryData("","-1", role, String.valueOf(CURRENT_YEAR - 1));
        ArrayList<Double> arrayCurrentYear = new ArrayList<Double>();

        List<TotalSampleVo> AreaSatisfactionByRole = reportDataMapper.queryAreaSatisfactionByXdAndRole("", role);
        String satisfiedRate = getSatisfiedRate(AreaSatisfactionByRole);
        arrayCurrentYear.add(Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1)));

        for (TotalSampleVo data : AreaSatisfactionByRole) {
            arrayCurrentYear.add(getPercentNo(Double.parseDouble(data.getValue().toString()), 5));
        }


        dataMap.put(String.valueOf(CURRENT_YEAR - 2), arrayYearBeforeLast);
        dataMap.put(String.valueOf(CURRENT_YEAR - 1), arrayLastYear);
        dataMap.put(String.valueOf(CURRENT_YEAR), arrayCurrentYear);
        return dataMap;
    }

    @Override
    public List<Double> querySatisfactionByRole(String role) {
        List<Double> list = reportDataMapper.querySatisfactionByRole(role);
        double total = 0.00;
        for (Double data : list) {
            total += data;
        }
        List<Double> temp = new ArrayList<>();
        for (Double data : list) {
            temp.add(getPercentNo(data, 5));
        }
        return temp;
    }

    @Override
    public String queryTotalSatisfactionByXd(String xd) {
        List<TotalSampleVo> result = reportDataMapper.queryAreaSatisfactionByXdAndRole(xd, "");
        double total = 0.00;
        for (TotalSampleVo totalSample : result) {
            total += Double.parseDouble(totalSample.getValue().toString());
        }
        //综合满意率
        String satisfiedRate = getSatisfiedRate(result);

        // 查询上年满意率
        List<TotalSampleVo> lastYear = reportDataMapper.queryAreaHistoryData(xd, "-1", String.valueOf(CURRENT_YEAR - 1));
        return "全市" + xd + "综合满意率" + satisfiedRate + "。其中，" + getAreaRateString(result,"") + currentYearcompareLastYear(result, lastYear,5,"");

    }

    @Override
    public Map<String, List<Double>> queryAreaSatisfactionPercentageByXdAndRole(String xd, String role) {
        Map<String, List<Double>> dataMap = new HashMap();
        List<Double> arrayYearBeforeLast = reportDataMapper.queryHistoryData("",xd, "".equals(role) ? "-1" : role, String.valueOf(CURRENT_YEAR - 2));
        List<Double> arrayLastYear = reportDataMapper.queryHistoryData("",xd, "".equals(role) ? "-1" : role, String.valueOf(CURRENT_YEAR - 1));
        ArrayList<Double> arrayCurrentYear = new ArrayList<Double>();
        List<TotalSampleVo> areaSatisfactionByRole = new ArrayList<>();
        if("".equals(role)) {
            areaSatisfactionByRole = reportDataMapper.queryAreaSatisfactionByXdAndRole(xd, role);

        }else {
            List<ProjectIndicatorsVo> projectIndicatorsVos = reportDataMapper.queryProjectIndicatorsByXdAndRole(xd, role);

            LinkedHashSet<String> areaList = projectIndicatorsVos.stream().map(ProjectIndicatorsVo::getAreaName).collect(Collectors.toCollection( LinkedHashSet::new ));
            for(String areaName : areaList) {
                String score = "";
                double total = 0.0;
                int length = 0;
                for(ProjectIndicatorsVo projectIndicatorsVo : projectIndicatorsVos) {
                    if(areaName.equals(projectIndicatorsVo.getAreaName())) {
                        length += 1;
                        total += projectIndicatorsVo.getScore();
                    }
                }
                score = String.format("%.8f", total/length );
                TotalSampleVo vo = new TotalSampleVo(areaName,score);
                areaSatisfactionByRole.add(vo);
            }

        }

        String satisfiedRate = getSatisfiedRate2(areaSatisfactionByRole);
        arrayCurrentYear.add(Double.parseDouble(satisfiedRate.substring(0, satisfiedRate.length() - 1)));
        if(areaSatisfactionByRole.size() == 11) {
            arrayCurrentYear.add(0.00);
        }
        for (TotalSampleVo data : areaSatisfactionByRole) {
            arrayCurrentYear.add(getPercentNo(Double.parseDouble(data.getValue().toString()), 5));
        }
        dataMap.put(String.valueOf(CURRENT_YEAR - 2), arrayYearBeforeLast);
        dataMap.put(String.valueOf(CURRENT_YEAR - 1), arrayLastYear);
        dataMap.put(String.valueOf(CURRENT_YEAR), arrayCurrentYear);
        return dataMap;
    }

    @Override
    public String queryTotalSatisfactionByXdAndRole(String xd, String role) {
        List<ProjectIndicatorsVo> projectIndicatorsVos = reportDataMapper.queryProjectIndicatorsByXdAndRole(xd, role);
        List<TotalSampleVo> result = new ArrayList<>();
        LinkedHashSet<String> areaList = projectIndicatorsVos.stream().map(ProjectIndicatorsVo::getAreaName).collect(Collectors.toCollection( LinkedHashSet::new ));
        for(String areaName : areaList) {
            String score = "";
            double total = 0.0;
            int length = 0;
            for(ProjectIndicatorsVo projectIndicatorsVo : projectIndicatorsVos) {
                if(areaName.equals(projectIndicatorsVo.getAreaName())) {
                    length += 1;
                    total += projectIndicatorsVo.getScore();
                }
            }
            score = String.format("%.8f", total/length );
            TotalSampleVo vo = new TotalSampleVo(areaName,score);
            result.add(vo);
        }

        //综合满意率
        String satisfiedRate = getSatisfiedRate2(result);
        if(role.equals("园长") || role.equals("人大代表/政协委员")) {
            return "全市" + xd + role + "综合满意率" + satisfiedRate + "。其中，" + getAreaRateString(result,role);
        }
        // 查询上年满意率
        List<TotalSampleVo> lastYear = reportDataMapper.queryAreaHistoryData(xd, role,String.valueOf(CURRENT_YEAR - 1));
        return "全市" + role + "综合满意率" + satisfiedRate + "。其中，" + getAreaRateString(result,role) + currentYearcompareLastYear(result,lastYear,5,"");

    }

    @Override
    public String queryProjectIndicatorsByXdAndRole(String xd, String role) {
        List<String> indexNameList = reportDataMapper.queryIndexNameByXdAndRole(xd, role);
        List<ProjectIndicatorsVo> pojectIndicatorsList = reportDataMapper.queryProjectIndicatorsByXdAndRole(xd, role);
        List<TotalSampleVo> result = getAvgProjectIndicators(indexNameList, pojectIndicatorsList);
        return getProjectIndicatorsString(result, xd, role);
    }

    @Override
    public Map<String, ArrayList<Double>> queryIndexSatisfactionByXdAndRole(String xd, String role) {
        Map<String, ArrayList<Double>> dataMap = new LinkedHashMap<>();
        List<String> indexNameList = reportDataMapper.queryIndexNameByXdAndRole(xd, role);
        if (CollectionUtils.isNotEmpty(indexNameList)) {
            List<ProjectIndicatorsVo> pojectIndicatorsList = reportDataMapper.queryProjectIndicatorsByXdAndRole(xd, role);
            List<ProjectIndicatorsVo> collect = pojectIndicatorsList.stream().filter(vo -> vo.getAreaName().equals("市属")).collect(Collectors.toList());
            List<ProjectIndicatorsVo> pojectIndicators = new ArrayList<>();
            if(CollectionUtils.isEmpty(collect)) {
                for(int i= 0;i<pojectIndicatorsList.size();i++) {
                    if(i == 0) {
                        for(String indexName: indexNameList) {
                            pojectIndicators.add(new ProjectIndicatorsVo("市属",indexName,0.0));
                        }
                    }
                    pojectIndicators.add(pojectIndicatorsList.get(i));
                }
            }else {
                pojectIndicators = pojectIndicatorsList;
            }
            List<TotalSampleVo> avg = getAvgProjectIndicators(indexNameList, pojectIndicators);
            for (String indexName : indexNameList) {

                ArrayList<Double> result = new ArrayList<Double>();
                for (TotalSampleVo totalSampleVo : avg) {
                    if (indexName.equals(totalSampleVo.getName())) {
                        result.add(Double.valueOf(totalSampleVo.getValue().toString()));
                    }
                }
                for (ProjectIndicatorsVo projectIndicatorsVo : pojectIndicators) {
                    if (indexName.equals(projectIndicatorsVo.getIndexName())) {
                        result.add(projectIndicatorsVo.getScore());
                    }
                }
                dataMap.put(indexName, result);
            }
        }
        return dataMap;
    }

    private String getPercent(double a, double b) {
        if (a == 0 || b == 0) {
            return "0%";
        }
        return String.format("%.2f", a / b * 100) + "%";
    }

    private Double getPercentNo(double a, double b) {
        if (a == 0 || b == 0) {
            return 0.0;
        }
        return Double.parseDouble(String.format("%.2f", a / b * 100));
    }

    private List<TotalSampleVo> getDataPercent(List<TotalSampleVo> data, boolean noPercentSign) {
        double total = 0;
        for (TotalSampleVo totalSampleVo : data) {
            total += Double.parseDouble(totalSampleVo.getValue().toString());
        }
        for (TotalSampleVo totalSampleVo : data) {
            if (noPercentSign) {
                totalSampleVo.setValue(getPercentNo(Double.parseDouble(totalSampleVo.getValue().toString()), total));
            } else {
                totalSampleVo.setValue(getPercent(Double.parseDouble(totalSampleVo.getValue().toString()), total));
            }

        }
        return data;
    }

    private List<Object> getDataValuePercent(List<String> data, boolean noPercentSign) {
        List<Object> result = new ArrayList<>();
        double total = 0;
        for (Object str : data) {
            total += Double.parseDouble(str.toString());
        }
        for (Object str : data) {
            if (noPercentSign) {
                result.add(getPercentNo(Double.parseDouble(str.toString()), total));
            } else {
                result.add(getPercent(Double.parseDouble(str.toString()), total));
            }

        }
        return result;
    }

    private String getSatisfiedRate(List<TotalSampleVo> data) {
        if (CollectionUtils.isEmpty(data)) {
            return "0%";
        }

        Iterator<TotalSampleVo> iterator = data.iterator();
        while(iterator.hasNext()) {
            TotalSampleVo vo = iterator.next();
            if(Double.valueOf(vo.getValue().toString()) == 0){
                iterator.remove();
            }
        }
        double totalRate = 0.0;
        for (TotalSampleVo totalSample : data) {
            totalRate = add(totalRate, Double.parseDouble(totalSample.getValue().toString()));
        }
        totalRate = div(totalRate,data.size(),4);
        return String.format("%.2f", getPercentNo(totalRate,5)) + "%";
    }

    private String getSatisfiedRate2(List<TotalSampleVo> data) {
        if (CollectionUtils.isEmpty(data)) {
            return "0%";
        }

        Iterator<TotalSampleVo> iterator = data.iterator();
        while(iterator.hasNext()) {
            TotalSampleVo vo = iterator.next();
            if(Double.valueOf(vo.getValue().toString()) == 0){
                iterator.remove();
            }
        }
        double totalRate = 0.0;
        for (TotalSampleVo totalSample : data) {
            totalRate = add(totalRate, Double.parseDouble(totalSample.getValue().toString()));
        }
        totalRate = div(totalRate,data.size(),8);
        return String.format("%.2f", getPercentNo(totalRate,5)) + "%";
    }

    public double add(double v1, double v2) {

        BigDecimal b1 = new BigDecimal(Double.toString(v1));

        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();

    }

    public double div(double v1, double v2, int scale) {

        if (scale < 0) {

            throw new IllegalArgumentException("The scale must be a positive integer or zero");

        }

        BigDecimal b1 = new BigDecimal(Double.toString(v1));

        BigDecimal b2 = new BigDecimal(Double.toString(v2));

        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

    }

    private String compareLastYear(String totalRate, String lastTotalRate) {
        double total = Double.parseDouble(totalRate.substring(0, totalRate.length() - 1));
        double lastTotal = Double.parseDouble(lastTotalRate.substring(0, lastTotalRate.length() - 1));
        if (total > lastTotal) {
            return "在上年基础上上升了" + String.format("%.2f", total - lastTotal) + "个百分点";
        } else if (total < lastTotal) {
            return "在上年基础上下降了" + String.format("%.2f", lastTotal - total) + "个百分点";
        } else {
            return "与上年持平";
        }
    }

    private String getAreaRateString(List<TotalSampleVo> data,String role) {
        if (CollectionUtils.isEmpty(data)) {
            return "";
        }
        List<TotalSampleVo> temp = new ArrayList<>();
        temp.addAll(data);
        Collections.sort(temp);
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < temp.size(); i++) {
            result.append(temp.get(i).getName()).append(getPercent(Double.parseDouble(temp.get(i).getValue().toString()), 5));
            if (i == 2) {
                result.append("依次靠前，");
            } else {
                result.append("、");
            }
        }

        if(role.equals("园长") || role.equals("人大代表/政协委员")) {
            return result.substring(0, result.length() - 1) + "依次靠后";
        }else {
            return result.substring(0, result.length() - 1) + "依次靠后。";
        }
    }

    private String getXdRateString(List<TotalSampleVo> data) {
        List<TotalSampleVo> temp = new ArrayList<>();
        temp.addAll(data);
        Collections.sort(temp);
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < temp.size(); i++) {
            result.append(temp.get(i).getName()).append("阶段").append(getPercent(Double.parseDouble(temp.get(i).getValue().toString()), 5 * 12)).append("、");
        }
        return result.substring(0, result.length() - 1) + "。";
    }

    private String getProjectIndicatorsString(List<TotalSampleVo> data, String xd, String role) {
        if (CollectionUtils.isEmpty(data)) {
            return "";
        }
        List<TotalSampleVo> temp = new ArrayList<>();
        temp.addAll(data);
        Collections.sort(temp);
        StringBuilder result = new StringBuilder();
        result.append("全市").append(xd).append(role).append("问卷").append(data.size()).append("个调查项目上的满意度水平从高到低分别为：");
        for (TotalSampleVo vo : temp) {
            result.append(vo.getName()).append(vo.getValue()).append("、");
        }
        return result.substring(0, result.length() - 1);
    }

    private List<TotalSampleVo> getAvgProjectIndicators(List<String> indexNameList, List<ProjectIndicatorsVo> ojectIndicatorsList) {
        if (CollectionUtils.isEmpty(indexNameList)) {
            return new ArrayList<>();
        } else {
            List<TotalSampleVo> result = new ArrayList<>();
            for (String indexName : indexNameList) {
                double total = 0.00;
                int count = 0;
                for (ProjectIndicatorsVo projectIndicatorsVo : ojectIndicatorsList) {
                    if (indexName.equals(projectIndicatorsVo.getIndexName())) {
                        total += projectIndicatorsVo.getScore();
                        count++;
                    }
                }
                if (total == 0) {
                    result.add(new TotalSampleVo(indexName, 0.00));
                }
                result.add(new TotalSampleVo(indexName, String.format("%.2f", total / count)));
            }
            return result;
        }
    }

    private String currentYearcompareLastYear(List<TotalSampleVo> currentYear, List<TotalSampleVo> lastYear,double divisor,String keyword) {

        if (CollectionUtils.isEmpty(currentYear)) {
            return "";
        }


        for (TotalSampleVo totalSampleVo : currentYear) {
            totalSampleVo.setValue(getPercentNo(Double.parseDouble(totalSampleVo.getValue().toString()), divisor));
        }

        List<String> up = new ArrayList<>();
        List<String> down = new ArrayList<>();
        List<String> keep = new ArrayList<>();

        for (TotalSampleVo current : currentYear) {
            for (TotalSampleVo last : lastYear) {
                if (current.getName().equals(last.getName())) {
                    if (Double.parseDouble(current.getValue().toString()) > Double.parseDouble(last.getValue().toString())) {
                        if(!"市属".equals(current.getName()) && !"贵安新区".equals(current.getName())) {
                            up.add(current.getName());
                        }
                    } else if (Double.parseDouble(current.getValue().toString()) < Double.parseDouble(last.getValue().toString())) {
                        if(!"市属".equals(current.getName()) && !"贵安新区".equals(current.getName())) {
                            down.add(current.getName());
                        }
                    } else {
                        if(!"市属".equals(current.getName()) && !"贵安新区".equals(current.getName())) {
                            keep.add(current.getName());
                        }
                    }
                    break;
                }
            }
        }

        String result = "";
        if(up.size() == 0 && down.size() == 0 && keep.size() == 0) {
            return result;
        }else if(up.size() != 0 && down.size() == 0 && keep.size() == 0) {
            if(keyword.equals("区县")) {
                result = "从区县看，其余区县均有所上升";
            }else if(keyword.equals("阶段")) {
                result = "与上年相比，各阶段综合满意度均有上升";
            }
            else {
                result = "与上年相比，其余区县均有上升";
            }
        }else if(up.size() == 0 && down.size() != 0 && keep.size() == 0){
            if(keyword.equals("区县")) {
                result = "从区县看，其余区县均有所下降";
            }else if(keyword.equals("阶段")) {
                result = "与上年相比，各阶段综合满意度均有下降";
            }
            else {
                result = "与上年相比，其余区县均有下降";
            }
        }else {
            if(keyword.equals("区县")) {
                result += "从区县看，";
            }else {
                result += "与上年相比，";
            }
            if(up.size() != 0) {
                for (String str : up) {
                    result += str;
                    result += "、";
                }
                result = result.substring(0, result.length() - 1);
                result += "有所上升，";
            }

            if(down.size() != 0) {
                for (String str : down) {
                    result += str;
                    result += "、";
                }
                result = result.substring(0, result.length() - 1);
                result += "有所下降，";
            }
            if(keep.size() != 0) {
                for (String str : keep) {
                    result += str;
                    result += "、";
                }
                result = result.substring(0, result.length() - 1);
                result += "保持不变，";
            }
            result = result.substring(0, result.length() - 1) ;
        }
        return result;
    }
}
